package com.example.onlinemusic.service;

import com.example.onlinemusic.mapper.LoveMusicMapper;
import com.example.onlinemusic.mapper.MusicMapper;
import com.example.onlinemusic.model.Music;
import com.example.onlinemusic.model.User;
import com.example.onlinemusic.tools.ResponseBodyMessage;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.binding.BindingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import jakarta.servlet.http.HttpSession;
import com.example.onlinemusic.tools.Constant;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class MusicService {

    @Value("${music.local.path}")
    private String SAVE_PATH;

    @Resource
    private MusicMapper musicMapper;

    @Resource
    private LoveMusicMapper loveMusicMapper;

    public ResponseBodyMessage<Boolean> uploadmusic(String singer, MultipartFile file, HttpServletRequest request,
                                                    HttpServletResponse response) throws IOException {
        // 1. 检查是否登录
        HttpSession httpSession = request.getSession(false);
        if (httpSession == null || httpSession.getAttribute(Constant.USERINFO_SESSION_KEY) == null) {
            System.out.println("没有登陆");
            return new ResponseBodyMessage<>(-1, "请登录后上传", false);
        }

        // 新增： 检查数据库中是否有当前音乐 (歌名 + 歌手)
        String fileNameAndType = file.getOriginalFilename();
        if (fileNameAndType == null || fileNameAndType.isEmpty()) {
            return new ResponseBodyMessage<>(-1, "无效的文件名", false);
        }
        int index = fileNameAndType.lastIndexOf(".");
        String title = fileNameAndType.substring(0, index);
        try {
            if (musicMapper.select(title, singer) != null) {
                return new ResponseBodyMessage<>(-1, "该歌曲已存在", false);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseBodyMessage<>(-1, "检查音乐失败", false);
        }


        // 2.上传到服务器
        System.out.println("fileNameAndType: " + fileNameAndType);
        String path = SAVE_PATH + fileNameAndType;
        File dest = new File(path);
        if (!dest.exists()) {
            dest.mkdir(); // 如果不存在就创建目录
        }
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseBodyMessage<>(-1,"服务器上传失败!",false);
        }

        // 3. 上传数据库
        // 1) 准备数据  2) 调用insert
//        int index = fileNameAndType.lastIndexOf(".");
//        String title = fileNameAndType.substring(0, index);
        User user = (User) httpSession.getAttribute(Constant.USERINFO_SESSION_KEY);
        int userid = user.getId();
        String url = "/music/get?path=" + title;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String time = simpleDateFormat.format(new Date());

        try {
            int ret = 0;
            ret = musicMapper.insert(title, singer, time, url, userid);
            if (ret == 1) {
                // 跳转页面
                response.sendRedirect("/list.html");
                return new ResponseBodyMessage<>(0,"数据库上传成功 !",true);
            } else {
                return new ResponseBodyMessage<>(-1,"数据库上传失败!",false);
            }
        } catch (BindingException e) {
            dest.delete();
            return new ResponseBodyMessage<>(-1,"数据库上传失败!",false);
        }

    }

    // 播放音乐时候：/music/get?path=xxx.mp3
    public ResponseEntity<byte[]> get(String path) {
        File file = new File(SAVE_PATH + path);
        byte[] a = null;
        try {
            a = Files.readAllBytes(file.toPath());
            if (a == null) {
                return ResponseEntity.badRequest().build();
            }
            return ResponseEntity.ok(a);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ResponseEntity.badRequest().build();
    }

    public ResponseBodyMessage<Boolean> deleteMusicById(String id) {
        // 1. 检查歌曲是否存在
        int iid = Integer.parseInt(id);
        // 2. 如果存在进行删除
        Music music = musicMapper.findMusicById(iid);
        if (music == null) {
            System.out.println("没有这个id的音乐");
            return new ResponseBodyMessage<>(-1, "没有要删除的音乐！", false);
        }
        // 2.1 删除数据库记录
        int ret = musicMapper.deleteMusicById(iid);
        if (ret == 1) {
            // 2.2 删除服务器上的数据
//                int index = music.getUrl().lastIndexOf("=");
//                String fileName = music.getUrl().substring(index + 1);
            String fileName = music.getTitle();
            File file = new File(SAVE_PATH + fileName + ".mp3");
            System.out.println("当前路径：" + file.getPath());
            if (file.delete()) {
                // 同步删除 lovemusic 中的音乐
                loveMusicMapper.deleteLoveMusicById(iid);
                return new ResponseBodyMessage<>(0, "服务器中的音乐删除成功！", true);
            } else {
                return new ResponseBodyMessage<>(-1, "服务器中的音乐删除失败！", false);
            }
        } else {
            return new ResponseBodyMessage<>(-1, "数据库中的音乐删除失败！", false);
        }
    }

    public ResponseBodyMessage<Boolean> deleteMusic(List<Integer> id) {
        System.out.println("所有的ID：" + id);
        int sum = 0;
        // 1. 检查歌曲是否存在
        for (int i = 0; i < id.size(); i++) {
            int musicId = id.get(i);
            Music music = musicMapper.findMusicById(musicId);
            if (music == null) {
                return new ResponseBodyMessage<>(-1, "没有要删除的音乐", false);
            }
            // 2. 如果存在进行删除
            int ret = musicMapper.deleteMusicById(musicId);
            if (ret == 1) {
                // 2.1 删除数据库记录
                int index = music.getUrl().lastIndexOf("=");
                String filename = music.getUrl().substring(index + 1);
                File file = new File(SAVE_PATH + filename + ".mp3");
                if (file.delete()) {
                    // 同步删除 lovemusic 中的音乐
                    loveMusicMapper.deleteLoveMusicById(musicId);
                    sum += ret;
                } else {
                    return new ResponseBodyMessage<>(-1, "服务器中的音乐删除失败！", false);
                }
            } else {
                return new ResponseBodyMessage<>(-1, "数据库中的音乐删除失败！", false);
            }
        }
        if (sum == id.size()) {
            System.out.println("整体删除成功!");
            return new ResponseBodyMessage<>(0, "音乐删除成功！", true);
        } else {
            System.out.println("整体删除失败!");
            return new ResponseBodyMessage<>(-1, "音乐删除失败！", false);
        }
    }

    public ResponseBodyMessage<List<Music>> findMusic(String musicName) {
        List<Music> musicList = null;
        if (musicName != null) {
            musicList = musicMapper.findMusicByName(musicName);
        } else {
            musicList = musicMapper.findMusic();
        }
        return new ResponseBodyMessage<>(0, "已查询到所有音乐", musicList);
    }
}
